package com.wisevar.thirdplatform.gateway.config;


import com.wisevar.thirdplatform.gateway.model.common.ApiResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.io.StringWriter;


@Controller
@RequestMapping(value = "error")
public class ErrorController implements org.springframework.boot.web.servlet.error.ErrorController {

    private static final Logger logger = LoggerFactory.getLogger(ErrorController.class);

    @Autowired
    private ErrorAttributes errorAttributes;


    @RequestMapping("500")
    @ResponseBody
    public ResponseEntity<Object> error500(HttpServletRequest request) {
        Throwable throwable = errorAttributes.getError(new ServletWebRequest(request));
        ApiResult result = ApiResult.serverError();
        if (throwable != null) {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            throwable.printStackTrace(pw);
            String errorLog = sw.toString();
            logger.error(errorLog);
        }

        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    @RequestMapping(value = "404")
    @ResponseBody
    public ResponseEntity<Object> error404(HttpServletRequest request) {
        HttpStatus status = getStatus(request);
        logger.info(">>>>>>>> 404请求，url: {}", getRequestUri(request));
        return new ResponseEntity<>(ApiResult.build(status.value(), "你请求的接口不存在"), status);
    }

    /**
     * 获取错误编码
     *
     * @param request
     * @return
     */
    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        try {
            return HttpStatus.valueOf(statusCode);
        } catch (Exception ex) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
    }

    /**
     * GET error requesturi
     *
     * @param request
     * @return
     */
    private String getRequestUri(HttpServletRequest request) {
        return (String) request.getAttribute("javax.servlet.error.request_uri");
    }

    @Override
    public String getErrorPath() {
        return "";
    }
}
